package com.atguigu.gulimall.product.service.impl;

import com.atguigu.common.to.MemberPriceTo;
import com.atguigu.common.to.SaveSpuBoundTo;
import com.atguigu.common.to.SkuFullReITo;
import com.atguigu.common.to.SkuLadderTo;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.product.dao.SpuInfoDao;
import com.atguigu.gulimall.product.entity.*;
import com.atguigu.gulimall.product.feign.CouponInfoFeignService;
import com.atguigu.gulimall.product.service.*;
import com.atguigu.gulimall.product.vo.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    protected SpuInfoDescService spuInfoDescService;

    @Autowired
    private SpuImagesService spuImagesService;

    @Autowired
    private CouponInfoFeignService couponInfoFeignService;

    @Autowired
    private AttrService attrService;

    @Autowired
    private ProductAttrValueService productAttrValueService;

    @Autowired
    private SkuInfoService skuInfoService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private SkuImagesService skuImagesService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        QueryWrapper<SpuInfoEntity> queryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty((String)(params.get("key")))){
            queryWrapper.and((v)->{
                v.eq("id",params.get("key")).or().like("spu_name",params.get("key"));
            });
        }
        if (!StringUtils.isEmpty((String)(params.get("catelogId"))) && !params.get("catelogId").equals("0")){
            queryWrapper.eq("catalog_id",params.get("catelogId"));
        }
        if (!StringUtils.isEmpty((String)(params.get("brandId"))) && !params.get("brandId").equals("0")){
            queryWrapper.eq("brand_id",params.get("brandId"));
        }
        if (!StringUtils.isEmpty((String) params.get("status"))){
            queryWrapper.eq("publish_status",params.get("status"));
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo spuInfoVo) {
        //1.先保存spu信息
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();

        spuInfoEntity.setSpuName(spuInfoVo.getSpuName());
        spuInfoEntity.setSpuDescription(spuInfoVo.getSpuDescription());
        spuInfoEntity.setCatalogId(spuInfoVo.getCatalogId());
        spuInfoEntity.setBrandId(spuInfoVo.getBrandId());
        spuInfoEntity.setWeight(spuInfoVo.getWeight());
        spuInfoEntity.setPublishStatus(spuInfoVo.getPublishStatus());
        spuInfoEntity.setCreateTime(new Date());
        this.save(spuInfoEntity);

        //2.保存spu信息介绍
        StringBuilder stringBuilder = new StringBuilder();

        //以逗号拼接两种方式
        //String streamDecript = spuInfoVo.getDecript().stream().map(String::valueOf).collect(Collectors.joining(","));
        spuInfoVo.getDecript().forEach(v -> {
            stringBuilder.append(v).append(",");
        });
        String toDecript = stringBuilder.deleteCharAt(stringBuilder.length() - 1).toString();

        //String join = String.join(",", spuInfoVo.getDecript());
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        spuInfoDescEntity.setDecript(toDecript);
        spuInfoDescService.save(spuInfoDescEntity);


        //3.保存spu图片信息
        spuInfoVo.getImages().forEach(v -> {
            SpuImagesEntity spuImagesEntity = new SpuImagesEntity();
            spuImagesEntity.setSpuId(spuInfoEntity.getId());
            spuImagesEntity.setImgUrl(v);
            spuImagesService.save(spuImagesEntity);
        });

        //4.保存商品spu积分设置信息，需要跨服务保存  sms_spu_bounds
        Bounds bounds = spuInfoVo.getBounds();
        SaveSpuBoundTo saveSpuBoundInfo = new SaveSpuBoundTo();
        saveSpuBoundInfo.setSpuId(spuInfoEntity.getId());
        saveSpuBoundInfo.setBuyBounds(bounds.getBuyBounds());
        saveSpuBoundInfo.setGrowBounds(bounds.getGrowBounds());
        couponInfoFeignService.saveSpuBounds(saveSpuBoundInfo);

        //5.保存spu的规格参数   pms_product_attr_value
        List<BaseAttrs> baseAttrs = spuInfoVo.getBaseAttrs();
        baseAttrs.forEach(v -> {
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();

            productAttrValueEntity.setAttrId(v.getAttrId());
            productAttrValueEntity.setSpuId(spuInfoEntity.getId());

            AttrRespVo attrRespVo = attrService.getAttrRespVoById(v.getAttrId());
            productAttrValueEntity.setAttrName(attrRespVo.getAttrName());//属性名称

            productAttrValueEntity.setAttrValue(v.getAttrValues());
            productAttrValueEntity.setQuickShow(v.getShowDesc());
            productAttrValueService.save(productAttrValueEntity);
        });

        //6.保存spu对应的sku信息
        //6.1 保存spu基本信息     pms_sku_info
        spuInfoVo.getSkus().forEach(v -> {
            SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
            skuInfoEntity.setSkuName(v.getSkuName());
            skuInfoEntity.setSkuTitle(v.getSkuTitle());
            skuInfoEntity.setSkuSubtitle(v.getSkuSubtitle());
            skuInfoEntity.setPrice(v.getPrice());
            skuInfoEntity.setBrandId(spuInfoVo.getBrandId());
            skuInfoEntity.setCatalogId(spuInfoVo.getCatalogId());
            skuInfoEntity.setSpuId(spuInfoEntity.getId());
            //保存默认图片信息
            v.getImages().forEach(defaImag->{
                if (defaImag.getDefaultImg()==1){
                    skuInfoEntity.setSkuDefaultImg(defaImag.getImgUrl());
                }
            });
            //TODO 以下字段待确认
            //"countStatus"
            //"priceStatus":0,
            skuInfoService.save(skuInfoEntity);

            //6.2 保存sku销售属性&值  pms_sku_sale_attr_value
            v.getAttr().forEach(attrV -> {
                SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                skuSaleAttrValueEntity.setAttrName(attrV.getAttrName());
                skuSaleAttrValueEntity.setAttrId(attrV.getAttrId());
                skuSaleAttrValueEntity.setAttrValue(attrV.getAttrValue());
                skuSaleAttrValueEntity.setSkuId(skuInfoEntity.getSkuId());
                skuSaleAttrValueService.save(skuSaleAttrValueEntity);
            });

            //6.3 保存sku图片信息   pms_sku_images
            v.getImages().forEach(imaV -> {
                SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                skuImagesEntity.setImgUrl(imaV.getImgUrl());
                skuImagesEntity.setDefaultImg(imaV.getDefaultImg());
                skuImagesService.save(skuImagesEntity);

            });

            //6.4 sku的优惠信息和满减信息
            //满减涉及到的字段 需要跨服务和数据库修改   sms_sku_full_reduction
            SkuFullReITo skuFullReITo = new SkuFullReITo();
            skuFullReITo.setSkuId(skuInfoEntity.getSkuId());
            skuFullReITo.setFullPrice(v.getFullPrice());
            skuFullReITo.setReducePrice(v.getReducePrice());
            couponInfoFeignService.saveSkuFullReInfo(skuFullReITo);

            //6.5 商品阶梯价格  需要跨服务和数据库修改 sms_sku_ladder
            //"fullCount":3,
            //"discount":1,
            //add_other  不叠加
            //price 折后价  需要自己计算  前端没有传该字段 默认为0
            SkuLadderTo skuLadderTo = new SkuLadderTo();
            skuLadderTo.setSkuId(skuInfoEntity.getSkuId());
            skuLadderTo.setFullCount(v.getFullCount());
            skuLadderTo.setDiscount(v.getDiscount());
            skuLadderTo.setAddOther(0);
            skuLadderTo.setPrice("0");
            couponInfoFeignService.saveSkuLInfo(skuLadderTo);

            //6.6 商品会员价格 sms_member_price
            List<MemberPriceTo> memberPriceTos = v.getMemberPrice().stream().map((memberPrice) -> {
                MemberPriceTo memberPriceTo = new MemberPriceTo();
                memberPriceTo.setMemberLevelName(memberPrice.getName());
                memberPriceTo.setMemberPrice(memberPrice.getPrice());
                memberPriceTo.setSkuId(skuInfoEntity.getSkuId());
                memberPriceTo.setMemberLevelId(memberPrice.getId());
                return memberPriceTo;
            }).collect(Collectors.toList());

            couponInfoFeignService.saveMemerPrice(memberPriceTos);
        });
    }

    public void saveSpuInfoUodate(SpuSaveVo spuInfoVo) {
        //1.先保存spu信息
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();

        spuInfoEntity.setSpuName(spuInfoVo.getSpuName());
        spuInfoEntity.setSpuDescription(spuInfoVo.getSpuDescription());
        spuInfoEntity.setCatalogId(spuInfoVo.getCatalogId());
        spuInfoEntity.setBrandId(spuInfoVo.getBrandId());
        spuInfoEntity.setWeight(spuInfoVo.getWeight());
        spuInfoEntity.setPublishStatus(spuInfoVo.getPublishStatus());
        spuInfoEntity.setCreateTime(new Date());
        this.save(spuInfoEntity);

        //2.保存spu信息介绍
        StringBuilder stringBuilder = new StringBuilder();

        //以逗号拼接两种方式
        //String streamDecript = spuInfoVo.getDecript().stream().map(String::valueOf).collect(Collectors.joining(","));
        spuInfoVo.getDecript().forEach(v -> {
            stringBuilder.append(v).append(",");
        });
        String toDecript = stringBuilder.deleteCharAt(stringBuilder.length() - 1).toString();

        //String join = String.join(",", spuInfoVo.getDecript());
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        spuInfoDescEntity.setDecript(toDecript);
        spuInfoDescService.save(spuInfoDescEntity);


        //3.保存spu图片信息
        spuInfoVo.getImages().forEach(v -> {
            SpuImagesEntity spuImagesEntity = new SpuImagesEntity();
            spuImagesEntity.setSpuId(spuInfoEntity.getId());
            spuImagesEntity.setImgUrl(v);
            spuImagesService.save(spuImagesEntity);
        });

        //4.保存商品spu积分设置信息，需要跨服务保存  sms_spu_bounds
        Bounds bounds = spuInfoVo.getBounds();
        SaveSpuBoundTo saveSpuBoundInfo = new SaveSpuBoundTo();
        saveSpuBoundInfo.setSpuId(spuInfoEntity.getId());
        saveSpuBoundInfo.setBuyBounds(bounds.getBuyBounds());
        saveSpuBoundInfo.setGrowBounds(bounds.getGrowBounds());
        couponInfoFeignService.saveSpuBounds(saveSpuBoundInfo);

        //5.保存spu的规格参数   pms_product_attr_value
        List<BaseAttrs> baseAttrs = spuInfoVo.getBaseAttrs();
        baseAttrs.forEach(v -> {
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();

            productAttrValueEntity.setAttrId(v.getAttrId());
            productAttrValueEntity.setSpuId(spuInfoEntity.getId());

            AttrRespVo attrRespVo = attrService.getAttrRespVoById(v.getAttrId());
            productAttrValueEntity.setAttrName(attrRespVo.getAttrName());//属性名称

            productAttrValueEntity.setAttrValue(v.getAttrValues());
            productAttrValueEntity.setQuickShow(v.getShowDesc());
            productAttrValueService.save(productAttrValueEntity);
        });

        //6.保存spu对应的sku信息
        //6.1 保存spu基本信息     pms_sku_info
        spuInfoVo.getSkus().forEach(v -> {
            SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
            skuInfoEntity.setSkuName(v.getSkuName());
            skuInfoEntity.setSkuTitle(v.getSkuTitle());
            skuInfoEntity.setSkuSubtitle(v.getSkuSubtitle());
            skuInfoEntity.setPrice(v.getPrice());
            skuInfoEntity.setBrandId(spuInfoVo.getBrandId());
            skuInfoEntity.setCatalogId(spuInfoVo.getCatalogId());
            skuInfoEntity.setSpuId(spuInfoEntity.getId());
            //保存默认图片信息
            v.getImages().forEach(defaImag->{
                if (defaImag.getDefaultImg()==1){
                    skuInfoEntity.setSkuDefaultImg(defaImag.getImgUrl());
                }
            });
            //TODO 以下字段待确认
            //"countStatus"
            //"priceStatus":0,
            skuInfoService.save(skuInfoEntity);

            //6.2 保存sku销售属性&值  pms_sku_sale_attr_value
            v.getAttr().forEach(attrV -> {
                SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                skuSaleAttrValueEntity.setAttrName(attrV.getAttrName());
                skuSaleAttrValueEntity.setAttrId(attrV.getAttrId());
                skuSaleAttrValueEntity.setAttrValue(attrV.getAttrValue());
                skuSaleAttrValueEntity.setSkuId(skuInfoEntity.getSkuId());
                skuSaleAttrValueService.save(skuSaleAttrValueEntity);
            });

            //6.3 保存sku图片信息   pms_sku_images  需要过滤图片为空的图片
            //v.getImages().forEach(imaV -> {
            //    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
            //    skuImagesEntity.setImgUrl(imaV.getImgUrl());
            //    skuImagesEntity.setDefaultImg(imaV.getDefaultImg());
            //    //skuImagesService.save(skuImagesEntity);
            //});
            List<Images> images = v.getImages();
            v.getImages().stream().map((vImage)->{
                SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                skuImagesEntity.setImgUrl(vImage.getImgUrl());
                skuImagesEntity.setDefaultImg(vImage.getDefaultImg());
                return skuImagesEntity;
            }).filter(vImageFilter->{
                return !StringUtils.isEmpty(vImageFilter.getImgUrl());
            }).collect(Collectors.toList());
           // skuImagesService.saveBatch();


            //6.4 sku的优惠信息和满减信息
            //满减涉及到的字段 需要跨服务和数据库修改   sms_sku_full_reduction
            SkuFullReITo skuFullReITo = new SkuFullReITo();
            skuFullReITo.setSkuId(skuInfoEntity.getSkuId());
            skuFullReITo.setFullPrice(v.getFullPrice());
            skuFullReITo.setReducePrice(v.getReducePrice());
            couponInfoFeignService.saveSkuFullReInfo(skuFullReITo);

            //6.5 商品阶梯价格  需要跨服务和数据库修改 sms_sku_ladder
            //"fullCount":3,
            //"discount":1,
            //add_other  不叠加
            //price 折后价  需要自己计算  前端没有传该字段 默认为0
            SkuLadderTo skuLadderTo = new SkuLadderTo();
            skuLadderTo.setSkuId(skuInfoEntity.getSkuId());
            skuLadderTo.setFullCount(v.getFullCount());
            skuLadderTo.setDiscount(v.getDiscount());
            skuLadderTo.setAddOther(0);
            skuLadderTo.setPrice("0");
            couponInfoFeignService.saveSkuLInfo(skuLadderTo);

            //6.6 商品会员价格 sms_member_price
            List<MemberPriceTo> memberPriceTos = v.getMemberPrice().stream().map((memberPrice) -> {
                MemberPriceTo memberPriceTo = new MemberPriceTo();
                memberPriceTo.setMemberLevelName(memberPrice.getName());
                memberPriceTo.setMemberPrice(memberPrice.getPrice());
                memberPriceTo.setSkuId(skuInfoEntity.getSkuId());
                memberPriceTo.setMemberLevelId(memberPrice.getId());
                return memberPriceTo;
            }).collect(Collectors.toList());

            couponInfoFeignService.saveMemerPrice(memberPriceTos);
        });
    }
}